//
//  BRDevicePopupViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2025/01/27.
//  Copyright © 2025 Brezze GWG. All rights reserved.
//

#import "BRDevicePopupViewController.h"
#import "BRAPI.h"
#import "BRRequestManager.h"
#import "BRHud.h"
#import "BROrderDetailViewController.h"
#import "BRToolsView.h"
#import "BROrderListModel.h"

typedef NS_ENUM(NSInteger, BRDevicePopupStatus) {
    BRDevicePopupStatusProcessing = 0,  // 处理中
    BRDevicePopupStatusSuccess = 1,    // 成功
    BRDevicePopupStatusFailed = 2      // 失败
};

@interface BRDevicePopupViewController ()

// 处理中状态UI
@property (nonatomic,strong) UIView *processingContainer;
@property (nonatomic,strong) UIImageView *processingIcon;
@property (nonatomic,strong) QMUILabel *processingLabel;
@property (nonatomic,strong) QMUILabel *processingTipLabel;
@property (nonatomic,strong) UIProgressView *progressView;
@property (nonatomic,strong) QMUILabel *progressLabel;
@property (nonatomic,strong) NSTimer *progressTimer;
@property (nonatomic,assign) CGFloat currentProgress;

// 成功状态UI
@property (nonatomic,strong) UIView *successContainer;
@property (nonatomic,strong) UIImageView *successIcon;
@property (nonatomic,strong) QMUILabel *successTitleLabel;
@property (nonatomic,strong) QMUILabel *successTipLabel;
@property (nonatomic,strong) QMUILabel *orderIdLabel;
@property (nonatomic,strong) QMUIButton *viewOrderButton;

// 失败状态UI
@property (nonatomic,strong) UIView *failedContainer;
@property (nonatomic,strong) UIImageView *failedIcon;
@property (nonatomic,strong) QMUILabel *failedTitleLabel;
@property (nonatomic,strong) QMUILabel *failedTipLabel;
@property (nonatomic,strong) QMUIButton *backButton;

@property (nonatomic,assign) BRDevicePopupStatus currentStatus;
@property (nonatomic,strong) NSString *orderId; // 成功时保存的订单ID

@end

@implementation BRDevicePopupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = Localized(@"popup_status");
    self.view.backgroundColor = UIColor.qd_backgroundColor;
    self.currentStatus = BRDevicePopupStatusProcessing;
    [self setUI];
    
    // 判断是否有orderUuid，如果没有则直接显示创建订单失败
    if (!self.orderUuid || self.orderUuid.length == 0) {
        NSLog(@"⚠️ [弹充电宝] orderUuid为空，直接显示创建订单失败");
        [self showCreateOrderFailedStatus];
        return;
    }
    
    // 有orderUuid，先检查订单状态，再决定是否调用弹出充电宝接口
    [self showProcessingStatus];
    [self checkOrderStatus];
}

- (void)dealloc {
    [self stopProgressTimer];
}

#pragma mark - UI Setup
- (void)setUI {
    // 处理中状态容器
    self.processingContainer = [[UIView alloc] init];
    self.processingContainer.backgroundColor = UIColorClear;
    [self.view addSubview:self.processingContainer];
    [self.processingContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    // 处理中图标（橙色设备图标）
    self.processingIcon = [[UIImageView alloc] init];
    self.processingIcon.image = [UIImage imageNamed:@"start_orange"];
    self.processingIcon.contentMode = UIViewContentModeScaleAspectFit;
    [self.processingContainer addSubview:self.processingIcon];
    [self.processingIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.processingContainer);
        make.top.equalTo(self.processingContainer).offset(100);
        make.width.height.mas_equalTo(120);
    }];
    
    // "正在处理..."文字
    self.processingLabel = [BRToolsView br_label:Localized(@"popup_processing") textColor:kColorTitle font:[UIFont fontB:18]];
    self.processingLabel.textAlignment = NSTextAlignmentCenter;
    [self.processingContainer addSubview:self.processingLabel];
    [self.processingLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.processingIcon.mas_bottom).offset(32);
        make.left.offset(20);
        make.right.offset(-20);
    }];
    
    // "请不要关闭页面"提示
    self.processingTipLabel = [BRToolsView br_label:Localized(@"popup_dontClose") textColor:UIColorMakeWithHex(@"#666666") font:[UIFont fontM:14]];
    self.processingTipLabel.textAlignment = NSTextAlignmentCenter;
    [self.processingContainer addSubview:self.processingTipLabel];
    [self.processingTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.processingLabel.mas_bottom).offset(8);
        make.left.offset(20);
        make.right.offset(-20);
    }];
    
    // 进度条
    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.progressView.progressTintColor = UIColorMakeWithHex(@"#FF6B00");
    self.progressView.trackTintColor = UIColorMakeWithHex(@"#E5E5E5");
    self.progressView.layer.cornerRadius = 2;
    self.progressView.layer.masksToBounds = YES;
    [self.processingContainer addSubview:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.processingTipLabel.mas_bottom).offset(24);
        make.left.offset(40);
        make.right.offset(-40);
        make.height.mas_equalTo(4);
    }];
    
    // 进度百分比
    self.progressLabel = [BRToolsView br_label:@"0%" textColor:kColorTitle font:[UIFont fontM:14]];
    self.progressLabel.textAlignment = NSTextAlignmentCenter;
    [self.processingContainer addSubview:self.progressLabel];
    [self.progressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.progressView.mas_bottom).offset(8);
        make.left.offset(20);
        make.right.offset(-20);
    }];
    
    // 成功状态容器
    self.successContainer = [[UIView alloc] init];
    self.successContainer.backgroundColor = UIColorClear;
    self.successContainer.hidden = YES;
    [self.view addSubview:self.successContainer];
    [self.successContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    // 成功图标
    self.successIcon = [[UIImageView alloc] init];
    self.successIcon.image = [UIImage imageNamed:@"Success1"];
    self.successIcon.contentMode = UIViewContentModeScaleAspectFit;
    [self.successContainer addSubview:self.successIcon];
    [self.successIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.successContainer);
        make.top.equalTo(self.successContainer).offset(100);
        make.width.height.mas_equalTo(120);
    }];
    
    // "租借成功"标题
    self.successTitleLabel = [BRToolsView br_label:Localized(@"home_success") textColor:kColorTitle font:[UIFont fontB:24]];
    self.successTitleLabel.textAlignment = NSTextAlignmentCenter;
    [self.successContainer addSubview:self.successTitleLabel];
    [self.successTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.successIcon.mas_bottom).offset(32);
        make.left.offset(20);
        make.right.offset(-20);
    }];
    
    // "请从机柜取出弹起的充电宝"提示
    self.successTipLabel = [BRToolsView br_label:Localized(@"popup_takePowerBank") textColor:UIColorMakeWithHex(@"#666666") font:[UIFont fontM:14]];
    self.successTipLabel.textAlignment = NSTextAlignmentCenter;
    self.successTipLabel.numberOfLines = 0;
    [self.successContainer addSubview:self.successTipLabel];
    [self.successTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.successTitleLabel.mas_bottom).offset(16);
        make.left.offset(40);
        make.right.offset(-40);
    }];
    
    // 订单ID显示
    self.orderIdLabel = [BRToolsView br_label:@"" textColor:UIColorMakeWithHex(@"#666666") font:[UIFont fontM:14]];
    self.orderIdLabel.textAlignment = NSTextAlignmentCenter;
    self.orderIdLabel.numberOfLines = 0;
    [self.successContainer addSubview:self.orderIdLabel];
    [self.orderIdLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.successTipLabel.mas_bottom).offset(24);
        make.left.offset(40);
        make.right.offset(-40);
    }];
    
    // "查看订单"按钮
    self.viewOrderButton = [BRToolsView br_btnBGImg:Localized(@"home_viewOrder")];
    [self.successContainer addSubview:self.viewOrderButton];
    [self.viewOrderButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.orderIdLabel.mas_bottom).offset(24);
        make.left.offset(40);
        make.right.offset(-40);
        make.height.mas_equalTo(52);
    }];
    [self.viewOrderButton addTarget:self action:@selector(viewOrderButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    
    // 失败状态容器
    self.failedContainer = [[UIView alloc] init];
    self.failedContainer.backgroundColor = UIColorClear;
    self.failedContainer.hidden = YES;
    [self.view addSubview:self.failedContainer];
    [self.failedContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    // 失败图标
    self.failedIcon = [[UIImageView alloc] init];
    self.failedIcon.image = [UIImage imageNamed:@"weijiesuan_icon"];
    self.failedIcon.contentMode = UIViewContentModeScaleAspectFit;
    [self.failedContainer addSubview:self.failedIcon];
    [self.failedIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.failedContainer);
        make.top.equalTo(self.failedContainer).offset(100);
        make.width.height.mas_equalTo(120);
    }];
    
    // "租借失败"标题
    self.failedTitleLabel = [BRToolsView br_label:Localized(@"home_failed") textColor:kColorTitle font:[UIFont fontB:24]];
    self.failedTitleLabel.textAlignment = NSTextAlignmentCenter;
    [self.failedContainer addSubview:self.failedTitleLabel];
    [self.failedTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.failedIcon.mas_bottom).offset(32);
        make.left.offset(20);
        make.right.offset(-20);
    }];
    
    // 失败提示
    self.failedTipLabel = [BRToolsView br_label:@"" textColor:UIColorMakeWithHex(@"#666666") font:[UIFont fontM:14]];
    self.failedTipLabel.textAlignment = NSTextAlignmentCenter;
    self.failedTipLabel.numberOfLines = 0;
    [self.failedContainer addSubview:self.failedTipLabel];
    [self.failedTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.failedTitleLabel.mas_bottom).offset(16);
        make.left.offset(40);
        make.right.offset(-40);
    }];
    
    // "返回"按钮
    self.backButton = [BRToolsView br_btnBGImg:Localized(@"popup_back")];
    [self.failedContainer addSubview:self.backButton];
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.failedTipLabel.mas_bottom).offset(40);
        make.left.offset(40);
        make.right.offset(-40);
        make.height.mas_equalTo(52);
    }];
    [self.backButton addTarget:self action:@selector(backButtonTapped) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - Status Management
/// 显示处理中状态
- (void)showProcessingStatus {
    self.currentStatus = BRDevicePopupStatusProcessing;
    self.processingContainer.hidden = NO;
    self.successContainer.hidden = YES;
    self.failedContainer.hidden = YES;
    
    // 重置进度
    self.currentProgress = 0.0;
    self.progressView.progress = 0.0;
    self.progressLabel.text = @"0%";
    
    // 开始进度条动画
    [self startProgressTimer];
}

/// 显示成功状态
- (void)showSuccessStatusWithOrderId:(NSString *)orderId {
    self.currentStatus = BRDevicePopupStatusSuccess;
    self.orderId = orderId;
    
    NSLog(@"📍 [弹充电宝] 显示成功状态，保存订单ID: %@", orderId);
    
    // 显示订单ID
    if (orderId && orderId.length > 0) {
        self.orderIdLabel.text = [NSString stringWithFormat:@"%@%@", Localized(@"order_orderNumberColon"), orderId];
    } else {
        self.orderIdLabel.text = @"";
    }
    
    [self stopProgressTimer];
    
    self.processingContainer.hidden = YES;
    self.successContainer.hidden = NO;
    self.failedContainer.hidden = YES;
}

/// 显示创建订单失败状态（没有orderUuid时）
- (void)showCreateOrderFailedStatus {
    self.currentStatus = BRDevicePopupStatusFailed;
    
    [self stopProgressTimer];
    
    self.processingContainer.hidden = YES;
    self.successContainer.hidden = YES;
    self.failedContainer.hidden = NO;
    
    // 设置创建订单失败的提示文字
    self.failedTipLabel.text = Localized(@"popup_createOrderFailed");
}

/// 显示失败状态（租借失败）
- (void)showFailedStatusWithMessage:(NSString *)message {
    self.currentStatus = BRDevicePopupStatusFailed;
    
    [self stopProgressTimer];
    
    self.processingContainer.hidden = YES;
    self.successContainer.hidden = YES;
    self.failedContainer.hidden = NO;
    
    // 如果有后端返回的错误信息，显示错误信息；否则显示默认提示
    if (message && message.length > 0) {
        self.failedTipLabel.text = message;
    } else {
        self.failedTipLabel.text = Localized(@"popup_scanAgain");
    }
}

#pragma mark - Progress Timer
/// 开始进度条定时器
- (void)startProgressTimer {
    [self stopProgressTimer];
    
    self.currentProgress = 0.0;
    self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.progressTimer forMode:NSRunLoopCommonModes];
}

/// 更新进度
- (void)updateProgress {
    // 进度条从0%到90%，然后等待接口返回
    if (self.currentProgress < 0.9) {
        self.currentProgress += 0.02; // 每次增加2%
        if (self.currentProgress > 0.9) {
            self.currentProgress = 0.9;
        }
    }
    
    self.progressView.progress = self.currentProgress;
    self.progressLabel.text = [NSString stringWithFormat:@"%.0f%%", self.currentProgress * 100];
}

/// 停止进度条定时器
- (void)stopProgressTimer {
    if (self.progressTimer) {
        [self.progressTimer invalidate];
        self.progressTimer = nil;
    }
}

#pragma mark - Network Request
/// 检查支付状态（先调用此接口，确认支付成功后再调用弹出充电宝接口）
/// 此接口只检查支付状态，不返回订单ID
- (void)checkOrderStatus {
    if (!self.orderUuid || self.orderUuid.length == 0) {
        NSLog(@"⚠️ [弹充电宝] orderUuid为空，直接显示创建订单失败");
        [self showCreateOrderFailedStatus];
        return;
    }
    
    NSString *url = [BRAPI checkPayOrder:self.orderUuid];
    
    NSLog(@"📍 [弹充电宝] 检查支付状态，orderUuid: %@", self.orderUuid);
    
    [[BRRequestManager shared] GET:url params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        NSLog(@"📍 [弹充电宝] 支付状态检查接口返回: %@", dataDict);
        
        // 检查是否有data字段（data存在表示支付成功）
        id data = dataDict[@"data"];
        
        if (!data) {
            // data为空，说明订单超时或支付失败
            NSLog(@"❌ [弹充电宝] 支付状态检查失败：data为空，订单超时或支付失败");
            [self showCreateOrderFailedStatus];
            return;
        }
        
        // data存在，说明支付成功，继续调用弹出充电宝接口
        NSLog(@"✅ [弹充电宝] 支付成功，开始调用弹出充电宝接口");
        [self requestPopup];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        NSLog(@"❌ [弹充电宝] 支付状态检查接口调用失败: code=%ld, msg=%@", (long)code, errMsg);
        // 接口调用失败，也认为支付失败，显示创建订单失败
        [self showCreateOrderFailedStatus];
    }];
}

/// 调用弹出充电宝接口
- (void)requestPopup {
    if (!self.deviceId || self.deviceId.length == 0) {
        // 不显示错误信息，只显示固定提示
        [self showFailedStatusWithMessage:nil];
        return;
    }
    
    NSString *url = [BRAPI rentboxPopup:self.deviceId];
    
    [[BRRequestManager shared] GET:url params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        NSLog(@"📍 [弹充电宝] 接口返回: %@", dataDict);
        
        // 检查业务错误码（即使HTTP状态码是200，业务code也可能表示错误）
        NSInteger businessCode = [dataDict[@"code"] integerValue];
        if (businessCode != 0 && businessCode != 200) {
            // 业务错误码不是0或200，认为是失败
            NSString *errorMsg = dataDict[@"msg"] ?: dataDict[@"message"] ?: @"请求失败";
            NSLog(@"❌ [弹充电宝] 业务错误: code=%ld, msg=%@", (long)businessCode, errorMsg);
            [self showFailedStatusWithMessage:errorMsg];
            return;
        }
        
        // 进度条到100%
        self.currentProgress = 1.0;
        self.progressView.progress = 1.0;
        self.progressLabel.text = @"100%";
        
        // 延迟一点时间显示成功状态
        // 只要支付接口成功，弹宝接口也成功，直接调用订单列表接口获取订单ID
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"✅ [弹充电宝] 弹出接口调用成功，调用订单列表接口获取订单ID");
            [self requestOrderListToGetOrderId];
        });
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        NSLog(@"❌ [弹充电宝] 接口调用失败: code=%ld, msg=%@", (long)code, errMsg);
        // 显示后端返回的错误信息
        [self showFailedStatusWithMessage:errMsg];
    }];
}

/// 调用订单列表接口获取订单ID（获取进行中的订单，取第一条）
- (void)requestOrderListToGetOrderId {
    // 使用新接口：POST /sw/app/rentbox/order/list.html/V2
    // status=0 表示进行中的订单
    NSDictionary *params = @{@"status": @(0)};
    
    NSLog(@"📍 [弹充电宝] 调用订单列表接口获取订单ID，参数: %@", params);
    
    [[BRRequestManager shared] POSTWithFormData:[BRAPI orderListV2] params:params succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        NSLog(@"📍 [弹充电宝] 订单列表接口返回: %@", dataDict);
        
        // 解析订单列表数据
        NSArray *orderArray = nil;
        if ([dataDict objectForKey:@"data"] && [[dataDict objectForKey:@"data"] isKindOfClass:[NSArray class]]) {
            orderArray = dataDict[@"data"];
        } else if ([dataDict isKindOfClass:[NSArray class]]) {
            orderArray = (NSArray *)dataDict;
        } else {
            orderArray = @[];
        }
        
        NSArray *orderList = [BROrderListModel mj_objectArrayWithKeyValuesArray:orderArray];
        
        if (orderList.count > 0) {
            // 取第一条订单（进行中的订单）
            BROrderListModel *firstOrder = orderList[0];
            NSString *orderId = nil;
            
            // 优先使用 orderId（int类型），如果没有则使用 uuid
            if (firstOrder.orderId > 0) {
                orderId = [NSString stringWithFormat:@"%ld", (long)firstOrder.orderId];
            } else if (firstOrder.uuid && firstOrder.uuid.length > 0) {
                orderId = firstOrder.uuid;
            } else if (firstOrder.orderNo && firstOrder.orderNo.length > 0) {
                orderId = firstOrder.orderNo;
            }
            
            if (orderId && orderId.length > 0) {
                NSLog(@"✅ [弹充电宝] 从订单列表获取到订单ID: %@", orderId);
                [self showSuccessStatusWithOrderId:orderId];
            } else {
                NSLog(@"❌ [弹充电宝] 订单列表中未找到订单ID");
                [self showFailedStatusWithMessage:@"未找到订单ID"];
            }
        } else {
            NSLog(@"❌ [弹充电宝] 订单列表为空，没有进行中的订单");
            [self showFailedStatusWithMessage:@"未找到进行中的订单"];
        }
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        NSLog(@"❌ [弹充电宝] 订单列表接口调用失败: code=%ld, msg=%@", (long)code, errMsg);
        [self showFailedStatusWithMessage:errMsg ?: @"获取订单列表失败"];
    }];
}

#pragma mark - Button Actions
/// 查看订单按钮点击（成功时）
- (void)viewOrderButtonTapped {
    if (self.orderId && self.orderId.length > 0) {
        // 先关闭当前弹充电宝页面
        NSArray *viewControllers = self.navigationController.viewControllers;
        NSMutableArray *newViewControllers = [NSMutableArray array];
        
        // 保留根视图控制器（首页）
        if (viewControllers.count > 0) {
            [newViewControllers addObject:viewControllers[0]];
        }
        
        // 创建订单详情页
        BROrderDetailViewController *orderDetailVC = [[BROrderDetailViewController alloc] init];
        orderDetailVC.orderNo = self.orderId;
        [newViewControllers addObject:orderDetailVC];
        
        // 设置新的视图控制器栈，这样订单详情返回时会直接回到首页
        [self.navigationController setViewControllers:newViewControllers animated:YES];
        
        NSLog(@"📍 [弹充电宝] 成功：已关闭弹充电宝页面，跳转到订单详情，订单详情返回时将回到首页");
    } else {
        [BRHud showAuto:Localized(@"popup_orderIdNotExist") inView:self.view];
    }
}

/// 返回按钮点击（失败时）
- (void)backButtonTapped {
    // 失败时：关闭当前页面并跳转到首页
    [self navigateToHome];
}

/// 跳转到首页（关闭当前页面）
- (void)navigateToHome {
    // 获取根视图控制器
    UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    // 如果是导航控制器，pop到根视图
    if ([rootVC isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)rootVC;
        [nav popToRootViewControllerAnimated:YES];
    } else if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 如果是TabBar控制器，切换到首页tab
        UITabBarController *tabBarController = (UITabBarController *)rootVC;
        tabBarController.selectedIndex = 0;
        // 如果首页是导航控制器，pop到根视图
        if ([tabBarController.selectedViewController isKindOfClass:[UINavigationController class]]) {
            UINavigationController *nav = (UINavigationController *)tabBarController.selectedViewController;
            [nav popToRootViewControllerAnimated:YES];
        }
    } else {
        // 其他情况，尝试pop当前导航控制器的所有视图
        if (self.navigationController) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
    
    NSLog(@"📍 [弹充电宝] 失败：已关闭弹充电宝页面并跳转到首页");
}

@end

